import * as React from "react";
import {
  Button,
  Image,
  SafeAreaView,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import { Dialog, Paragraph, Portal, Provider } from "react-native-paper";
import { DOMAIN_URL, deptInfoGet, noticeUnread, newsList, eventList, studyList, newsRecent } from "../util/api";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useState } from "react";
import { style } from "../theme";
import { PAGENAME } from "../util/PageName";

class HomeScreen extends React.Component {


  constructor(props) {
    super(props);
    this.state = {
      deptInfo: "",
      score: "",
      description: "",
      visible: false,
      isAdmin: false,
      images: [],
      notice: {},
      newsList: [],
      eventInfo: {},
      eventImage: {},
      studyGarden: [],
    };
    AsyncStorage.getItem("isAdmin").then(value => {
      console.log("this.state.isAdmin", value);
      this.setState({
        isAdmin: value == "true" ? true : false,
      });
    });
    this.loadDeptInfo();
  }


  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log("componentDidUpdate");
  }

  componentDidMount() {
    this.subscription = this.props.navigation.addListener("focus", () => {
      // do something
      console.log("Home loading");
      this.getNewList();
      this.getActivityList();
      this.getStudyGarden();
      this.checkNoticeRead();
    });
  }

  checkNoticeRead() {
    noticeUnread(null).then((res) => {
      console.log(res);
      if (res.data) {
        console.log(res.data);
        // setNotice(res.data);
        this.setState({ visible: true });
        this.setState({
          notice: res.data,
        });
      }
    });
  }

  hideDialog = () => {
    // setVisible(false);
    this.setState({ visible: false });
    this.props.navigation.push(PAGENAME.NOTICE_DETAIL, { item: this.state.notice });
  };

  getNewList = () => {
    newsRecent({}).then(res => {
      this.setState({ newsList: res.data });
    });
  };

  getActivityList = () => {
    eventList("1", "1").then(res => {
      this.setState({ eventInfo: res.data[0] });
      if (this.state.eventInfo?.imageDetails) {
        this.setState({ eventImage: this.state.eventInfo?.imageDetails[0] });
      }
    });
  };

  getStudyGarden = () => {
    // deptInfo
    studyList("1", "3").then(res => {
      console.log(res.data);
      this.setState({
        studyGarden: res.data,
      });
    });
  };

  loadDeptInfo = () => {
    // deptInfo
    deptInfoGet().then(res => {
      console.log("dept info ", res);
      this.setState({
        deptInfo: res.data,
      });
    });
  };


  render() {
    // <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
    //   <Text>Home screen</Text>
    //   <Button
    //     title="Go to Details"
    //     onPress={() => navigation.navigate('Details')}
    //   />
    // </View>
    // <ImageBackground
    //   source={require('../assets/images/bg.JPG')} // 替换为您自己的背景图路径
    //   style={{ flex: 1 }}
    //   imageStyle={{ opacity: 0.4 }} // 修改透明度，范围为0（完全透明）到1（完全不透明）
    // >
    const { navigation } = this.props;
    return <SafeAreaView style={styles.container}>

      <ScrollView style={styles.scrollView}>
        <Provider>
          <View>
            {/*<Button onPress={showDialog}>Show Dialog</Button>*/}
            <Portal>
              <Dialog visible={this.state.visible} onDismiss={this.hideDialog}>
                <Dialog.Title>公告</Dialog.Title>
                <Dialog.Content>
                  <Paragraph>
                    {this.state.notice.noticecontent}
                  </Paragraph>
                </Dialog.Content>
                <Dialog.Actions>
                  <Button onPress={this.hideDialog} title="查看" />
                </Dialog.Actions>
              </Dialog>
            </Portal>
          </View>
          {/*<Button style={{marginTop: 30}} onPress={showModal}>*/}
          {/*  Show*/}
          {/*</Button>*/}
          <View
            style={{
              paddingVertical: 8,
              flexDirection: "row",
              alignItems: "center",
              justifyContent: "space-between",
              backgroundColor: "#fff2f1",
            }}>
            <TouchableOpacity
              style={styles.fab}
              onPress={() => {
                navigation.push("Active");
              }}>
              <Image
                style={{ width: 45, height: 45 }}
                source={require("../assets/images/icon/active.png")}></Image>
              <Text>学习活动</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.fab}
              onPress={() => {
                navigation.push("Lesson");
              }}>
              <Image
                style={{ width: 45, height: 45 }}
                source={require("../assets/images/icon/lesson.png")}></Image>
              <Text>线上课程</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.fab}
              onPress={() => {
                navigation.push("Score");
              }}>
              <Image
                style={{ width: 45, height: 45 }}
                source={require("../assets/images/icon/score.png")}></Image>

              <Text>积分公示</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.fab}
              onPress={() => {
                navigation.push("Honor");
              }}>
              <Image
                style={{ width: 45, height: 45 }}
                source={require("../assets/images/icon/honor.png")}></Image>

              <Text>荣誉申报</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.fab}
              onPress={() => {
                navigation.push("Notice");
              }}>
              <Image
                style={{ width: 45, height: 45 }}
                source={require("../assets/images/icon/notice.png")}></Image>
              <Text>支部公告</Text>
            </TouchableOpacity>
          </View>

          <View style={{ marginHorizontal: 8 }}>
            <View style={styles.currentActivity}>

              <View style={styles.homeTitle}>
                <Text style={style.subTitle}>最新活动</Text>
                <TouchableOpacity onPress={() => {
                  this.props.navigation.push(PAGENAME.ACTIVE);
                }}>
                  <Image source={require("../assets/images/icon/more.png")} style={styles.buttonIcon} />
                </TouchableOpacity>
              </View>
              <TouchableOpacity onPress={() => {
                this.state.eventInfo &&  this.props.navigation.push(PAGENAME.ACTIVE_DETAIL, { data: this.state.eventInfo });
              }}>
                <View
                  style={{
                    // flexDirection: 'row',
                    marginVertical: 4,
                    alignSelf: "center",
                    alignItems: "center",
                    alignContent: "center",
                    justifyContent: "space-around",
                  }}>
                  <View
                    style={{
                      width: "100%",
                      alignItems: "center",
                    }}>
                    <Image
                      style={{ width: 350, height: 150 }}
                      source={{
                        uri: `${DOMAIN_URL}/${this.state.eventImage?.path}`,
                      }}></Image>
                    <Text style={styles.activityFooter} numberOfLines={1}>
                      {this.state.eventInfo?.name}
                    </Text>
                  </View>

                </View>
              </TouchableOpacity>
            </View>

            <View style={{ paddingHorizontal: 16, backgroundColor: "#fff2f1" }}>
              <View style={{ marginTop: 24 }}>
                <View style={{ height: 12, display: "flex", flexDirection: "row", alignSelf: "center" }}>
                  <View style={{ height: 12, width: 40, backgroundColor: "#EBDAAD" }}></View>
                </View>
                <View style={{ height: 1, width: "100%", backgroundColor: "#EBDAAD", marginTop: -6 }}></View>
              </View>

              <View style={{ marginTop: 16 }}>
                <View style={styles.homeTitle}>
                  <Text style={style.pageTitle}>{this.state.deptInfo?.companyname}</Text>
                  {
                    this.state.isAdmin && <View>
                      <TouchableOpacity onPress={() => {
                        this.props.navigation.push(PAGENAME.COMPANY_EDIT);
                      }}>
                        <Image source={require("../assets/images/icon/edit_note.png")} style={{
                          width: 24, // 图标宽度
                          height: 24, // 图标高度
                        }} />
                      </TouchableOpacity>
                    </View>
                  }
                </View>
                <Text style={styles.dangzhibu}>
                  {this.state.deptInfo?.companycontent}
                </Text>
              </View>
              <View style={{ height: 46, marginTop: 10 }}>
                <View style={{ height: 12, display: "flex", flexDirection: "row", alignSelf: "center" }}>
                  <View style={{ height: 12, width: 40, backgroundColor: "#EBDAAD" }}></View>
                </View>
                <View style={{ height: 1, width: "100%", backgroundColor: "#EBDAAD", marginTop: -6 }}></View>
              </View>
            </View>


            <View style={styles.homeTitle}>
              <Text style={style.subTitle}>支部动态</Text>
              <TouchableOpacity onPress={() => {
                this.props.navigation.push(PAGENAME.BRANCH);
              }}>
                <Image source={require("../assets/images/icon/more.png")} style={styles.buttonIcon} />
              </TouchableOpacity>
            </View>
            <View
              style={{
                // flexDirection: 'row',
                // alignItems: 'center',
                justifyContent: "space-between",
              }}>
              {this.state.newsList?.map((k, index) => {
                return (
                  <TouchableOpacity onPress={() => {
                    this.props.navigation.push(PAGENAME.BRANCH_DETAIL, { newsId: k.newsid });
                  }}>
                    <View style={styles.indexDataRow} key={"event:" + index}>
                      <Image
                        style={{ width: 45, height: 45, marginRight: 8 }}
                        source={{
                          uri: `${DOMAIN_URL}${k?.attachmentsDetail[0]?.path}`,
                        }}
                      />
                      <View>
                        <Text>{k.newsTitle}</Text>
                        <Text style={{ marginTop: 4 }}>{k.starttime}</Text>
                      </View>
                    </View>
                  </TouchableOpacity>
                );
              })}
            </View>
            <View style={styles.homeTitle}>
              <Text style={style.subTitle}>学习园地</Text>
              <TouchableOpacity onPress={() => {
                this.props.navigation.push(PAGENAME.LEARN);
              }}>
                <Image source={require("../assets/images/icon/more.png")} style={styles.buttonIcon} />
              </TouchableOpacity>
            </View>
            <View
              style={{
                // flexDirection: 'row',
                // alignItems: 'center',
                justifyContent: "space-between",
              }}>
              <View
                style={{
                  // flexDirection: 'row',
                  // alignItems: 'center',
                  justifyContent: "space-between",
                }}>
                {this.state.studyGarden?.map((i, index) => {
                  return (
                    <TouchableOpacity
                      onPress={() =>
                        this.props.navigation.push(PAGENAME.LEARN_DETAIL, { data: i })
                      }>
                      <View style={styles.indexDataRow} key={"event:" + index}>
                        <Image
                          style={{ width: 45, height: 45, marginRight: 8 }}
                          source={{
                            /* "./file/images/53d23de14cf646fdb05b2c38bfa9f97a.JPG",  */
                            uri: `${DOMAIN_URL}${i.frontCoverDetail?.path}`,
                          }}
                        />
                        <View>
                          <Text>{i.name}</Text>
                          <Text style={{ marginTop: 4 }}>2024-03-11 15:00:00</Text>
                        </View>
                      </View>

                    </TouchableOpacity>

                  );
                })}
              </View>
            </View>
          </View>

        </Provider>
      </ScrollView>
    </SafeAreaView>;
    // </ImageBackground>

  };
}

const styles = StyleSheet.create({

  buttonIcon: {
    width: 20, // 图标宽度
    height: 20, // 图标高度
  },
  buttonText: {
    color: "white", // 文本颜色
    fontWeight: "bold",
  },
  activityFooter: {
    marginTop: 10,
  },
  fab: {
    // position: 'absolute',
    // margin: 16,
    // right: 0,
    // bottom: 0,
    width: 70,
    height: 70,
    justifyContent: "center",
    alignItems: "center",
  },
  container: {
    flex: 1,
    // marginVertical: 8,
    backgroundColor: "#fbfcfe",
    // paddingTop: 16,
    // paddingTop: StatusBar.currentHeight,
  },
  scrollView: {
    // backgroundColor: 'pink',
    // marginHorizontal: 8,
  },
  text: {
    fontSize: 42,
  },
  indexDataRow: {
    margin: 4,
    flexDirection: "row",
  },
  homeTitle: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    // margin: 8,
  },
  dangzhibu: {
    padding: 5,
  },
  currentActivity: {
    marginTop: 10,
  },
  activityImage: {
    borderWidth: 3,
    borderColor: "#667289",
    padding: 5,

  },
  homeTitleText: {
    fontWeight: "bold",
    fontSize: 16,
  },
});

export default HomeScreen;
